package com.example.utils;

import java.util.Date;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.experimental.UtilityClass;

@UtilityClass
public class JwtUtil {
    private static final String SECRET_KEY = "HomeBuddy";
    private static final long EXPIRATION_TIME = 1000 * 60 * 60;

    public String generateToken(String openId) {
        return Jwts.builder()
                .setSubject(openId)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();
    }

    public String generateTokenByUserId(Integer userId) {
        return Jwts.builder()
            .setSubject(String.valueOf(userId))
            .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
            .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
            .compact();
    }

    public String getOpenIdFromToken(String token) {
        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getSubject();
    }

    public Integer getUserIdFromToken(String token) {
        return Integer.valueOf(Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getSubject());
    }

    public boolean validateToken(String token) {
        try {
            String openId = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody().getSubject();
            return openId.equals(UserHelper.getOpenId());
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        String token = generateToken("123ljahsdjkfahlksdf");
        System.out.println(token);
    }
}
